package lc.q350_400;

import java.util.ArrayList;
import java.util.List;

public class Q388 {

    class Node {
        String path;
        Node parent;
        List<Node> subNodes;

        private int size;

        public Node(String path, Node parent, List<Node> subNodes, int size) {
            this.path = path;
            this.parent = parent;
            this.subNodes = subNodes;
            this.size = size;
        }
    }

    public int lengthLongestPath(String input) {
        Node parent = new Node("", null, new ArrayList<>(), 0);
        int n = -1;
        int maxLen = 0;
        String[] split = input.split("\n");
        for (String s : split) {
            int tn = s.lastIndexOf("\t");
            if (tn > n) {
                // 进一位
                parent = parent.subNodes.get(parent.subNodes.size() - 1);
            } else {
                // 退位
                for (int i = 0; i < n - tn; i++) {
                    parent = parent.parent;
                }
            }
            String path = s.substring(tn + 1);
            n = tn;
            Node node = new Node(path, parent, new ArrayList<>(), parent.size + 1 + path.length());
            parent.subNodes.add(node);
            if (path.contains(".")) {
                maxLen = Integer.max(node.size - 1, maxLen);
            }
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(new Q388().lengthLongestPath("file1.txt\nfile2.txt\nlongfile.txt"));
    }
}
